﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using System.IO;

using LumiSoft.Net.POP3.Client;
using LumiSoft.Net.Mime;
using Entity;
using Utility;

namespace POPService
{
    public class POPService
    {
        public static POP3_Client Connection(UserAccount _ua)
        {
            string[] _temp = _ua.MailAddress.Split('@');

            try
            {  
                POP3_Client _service = new POP3_Client();
                _service.Connect(_ua.ReciveServer, _ua.ReciveServerPort);
                _service.Authenticate(_temp[0], _ua.MailPassword, false);
                return _service;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        public static MailList GetMailList(UserAccount _ua)
        {
            POP3_Client _service = ConnectionCache.Connections["POP_" + _ua.MailAddress] as POP3_Client;
            //List<Mail> _mailList = new List<Mail>();
            MailList _mailList = new MailList();
            List<string> _mailInDB = new List<string>();//数据库里已有邮件列表，用来存现存邮件的UID
            _mailInDB.Add("1tbivxgjYk2-34AeLQAAs4");
            //List<MimeEntry> _mime = new List<MimeEntry>();
            //MimeEntry _mm = new MimeEntry();
            
            POP3_MessagesInfo _infos = _service.GetMessagesInfo();
            //for (int i = 0; i < _infos.Count; i++)
            for (int i = _infos.Count - 1; i >= 0; i--)
            {
                //string fdfdfdfsa = _infos.Messages[i].MessegeID;
                //bool ttt = _mailInDB.Contains(_infos.Messages[i].MessegeID);
                if (!_mailInDB.Contains(_infos.Messages[i].MessegeID))
                {
                    POP3_MessageInfo _info = _infos.Messages[i];
                    byte[] _byte = _service.GetMessage(_info.MessageNr);
                    //byte[] _byte = _service.GetMessage(17);//#11,#16为QP编码//#13乱码//#6解码有问题
                    _mailList.MailItems.Add(MailTools.MailParser(_info.MessegeID, _byte));
                    //_mailList.Add(MailParser(_info.MessegeID, _byte));
                    //MailParser(_info.MessegeID, _byte);
                }
                //POP3_MessageInfo _info = _infos.Messages[i];

                //byte[] _byte = _service.GetMessage(_info.MessageNr);

                //string sss = Encoding.UTF8.GetString(_byte);
                //string[] ffff = Regex.Split(sss, "\r\n\r\n");
                //string ffdd = MimeParser.ParseHeaderField("content-type", ffff[0]);
                //string sdfa = MimeParser.ParseHeaderFiledSubField("content-type", "charset", ffff[0]);
            }
            

            return _mailList;
        }

    }
}
